#! /usr/bin/env python2.5
import sys
import math
import pprint

primeList = []
            
def gen(length):
    #global minsum
    if length == 0:
        yield []
    else:
        for item in gen(length-1):
            #j=0
            #while primeList[j]<minsum:
            #    j+=1
            if item:
                #a = [k for k in primeList if (k>item[-1] and k < minsum)]
                a = list(primeList[primeList.index(item[-1]):])
            else:
                #a = [k for k in primeList if k<minsum]
                a = list(primeList)
            #a=list(primeList)
            for i in a:
                if i>=minsum:
                    break
                if isGroup(item + [i]):
                    yield (item + [i])
    
def isGroup(l):
    for i in l[:-1]:
        if not (isPrime(int(str(i)+str(l[-1]))) and isPrime(int(str(l[-1])+str(i)))):
            return False
    return True
    
        
def isPair(l5, l2):
    return isPrime(int(str(l5[l2[0]])+str(l5[l2[1]]))) and isPrime(int(str(l5[l2[1]])+str(l5[l2[0]])))
    
def main():
    groupsize = int(sys.argv[1])
    a = int(sys.argv[2])
    global primeList
    global minsum
    minsum = 1000000
    g = gen(groupsize)
    for a in g:
        if minsum > sum(a):
            minsum = sum(a)
        print sum(a)
        print a
        sys.stdout.flush()
    return
    lall = []
    for l5 in comb(primeList[:a], groupsize):
        isgroup = True
        for l2 in comb(range(groupsize), 2):
            if not isPair(l5, l2):
                isgroup = False
                break
        if isgroup:
            lall.append(l5)
            break
        #if len(lall) > 5:
        #    break
    pprint.pprint(lall)
    
if __name__ == '__main__':
    main()

init()
